﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;

namespace Relocation
{
    [RunInstaller(true)]
    public partial class programInstaller : Installer
    {
        public programInstaller()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 连接字符串
        /// </summary>
        private const string connectionString = @"Data Source=.\SQLEXPRESS;Initial Catalog=master;Integrated Security=True;MultipleActiveResultSets=True";

        /// <summary>
        /// 数据库名
        /// </summary>
		private const string DataBaseName = "RelocationServer";
		private const string _MdfPath = @"\App_Data\RelocationServer.mdf";
		private const string _LdfPath = @"\App_Data\RelocationServer_log.LDF";

        public override void Install(IDictionary stateSaver)
        {
            base.Install(stateSaver);

            //得到程序的安装路径
            Assembly Asm = Assembly.GetExecutingAssembly();
            System.IO.FileInfo FileInfo = new System.IO.FileInfo(Asm.Location);

            string path = FileInfo.DirectoryName;

            //string connectionString =@"Data Source=.\SQLEXPRESS;Initial Catalog=Relocation;Integrated Security=True;MultipleActiveResultSets=True";

            string MdfFileName = path + _MdfPath;
            string LdfFileName = path + _LdfPath;

            if (!File.Exists(MdfFileName))
                return;

            if (!File.Exists(LdfFileName))
                return;
            
            SqlConnection conn = new SqlConnection(connectionString);
            conn.Open();

            //如果数据库存在
            if (DataBaseExists(conn, DataBaseName))
            {
                conn.Close();
                return;
            }

            SqlCommand comm = new SqlCommand();
            comm.Connection = conn;
            comm.CommandText = "sp_attach_db";//系统数据库master 中的一个附加数据库存储过程。

            comm.Parameters.Add(new SqlParameter(@"dbname", SqlDbType.NVarChar));
            comm.Parameters[@"dbname"].Value = DataBaseName;
            comm.Parameters.Add(new SqlParameter(@"filename1", SqlDbType.NVarChar));  //一个主文件mdf，一个或者多个日志文件ldf，或次要文件ndf
            comm.Parameters[@"filename1"].Value = MdfFileName;
            comm.Parameters.Add(new SqlParameter(@"filename2", SqlDbType.NVarChar));
            comm.Parameters[@"filename2"].Value = LdfFileName;

            try
            {
                comm.CommandType = CommandType.StoredProcedure;
                comm.ExecuteNonQuery();
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                conn.Close();
            }

        }

        public override void Uninstall(IDictionary savedState)
        {
            SqlConnection conn = new SqlConnection(connectionString);
            try
            {
                conn.Open();

                if (DataBaseExists(conn, DataBaseName))
                {

                    SqlCommand comm = new SqlCommand();
                    comm.Connection = conn;
                    comm.CommandText = @"sp_detach_db";//系统数据库master 中的一个分离数据库存储过程。

                    comm.Parameters.Add(new SqlParameter(@"dbname", SqlDbType.NVarChar));
                    comm.Parameters[@"dbname"].Value = DataBaseName;

                    comm.CommandType = CommandType.StoredProcedure;
                    comm.ExecuteNonQuery();
                }
            }
            catch (Exception ex)
            {                
                MessageBox.Show(ex.Message, "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            finally
            {
                conn.Close();
            }

            base.Uninstall(savedState);
        }



        /// <summary>
        /// 根据数据库名判断目标数据库是否存在
        /// </summary>
        /// <param name="sqlConnection">sqlConnection</param>
        /// <param name="dataBaseName">数据库名</param>
        /// <returns>如果为true,则说明数据库存在</returns>
        private bool DataBaseExists(SqlConnection sqlConnection, string dataBaseName)
        {
            string sqlStr = "SELECT COUNT(*) name FROM master.dbo.sysdatabases where name='" + dataBaseName.Replace("'", "''") + "';";
            try
            {
                SqlCommand comm = new SqlCommand();
                comm.Connection = sqlConnection;
                comm.CommandText = sqlStr;

                if (!sqlConnection.State.Equals(ConnectionState.Open))
                    sqlConnection.Open();
                object obj = comm.ExecuteScalar();
                if (obj != null)
                {
                    if (Convert.ToInt32(obj) > 0)
                        return true;
                }
            }
            catch (Exception)
            { throw; }
            return false;
        }
    }
}
